package com.clp.protocol.iec104.apdu.asdu.infoobj.infoelem;

import com.clp.protocol.iec104.definition.TypeTag;
import com.clp.protocol.core.pdu.nbytepdu.BaseNBytePduClip;
import com.clp.protocol.core.pdu.ByteToStringFormat;
import com.clp.protocol.core.utils.ByteUtil;
import io.netty.buffer.ByteBuf;
import lombok.Getter;

import java.util.Objects;
import java.util.function.Consumer;


/**
 * 累积量（遥脉）
 */
@Getter
public class M_IT_NA_1_InfoElem extends InfoElem {
    /**
     * 遥脉值为整数
     */
    private long longVal;

    public M_IT_NA_1_InfoElem() {
        this(-1);
    }

    public M_IT_NA_1_InfoElem(long longVal) {
        super(TypeTag.M_IT_NA_1);
        this.longVal = longVal;
    }

    @Override
    public M_IT_NA_1_InfoElem refreshFrom(ByteBuf buf) {
        this.longVal = buf.readIntLE() & 0xFFFFFFFFL;
        return this;
    }

    @Override
    public boolean isValid() {
        return true;
    }

    @Override
    public void writeBytesTo(ByteBuf buf) {
        buf.writeIntLE((int) longVal);
    }

    @Override
    public void writeFormattedByteStringsTo(StringBuilder sb, String frameClipBytesSeparator, String byteSeparator, ByteToStringFormat byteFormat) {
        byte[] longValBytes = ByteUtil.longToBytes4LE(longVal);
        sb.append(byteFormat.format(longValBytes[0]));
        for (int i = 1; i < longValBytes.length; i++) {
            sb.append(byteSeparator).append(byteFormat.format(longValBytes[i]));
        }
    }

    @Override
    public void writeSimpleDescriptionTo(StringBuilder sb) {
        sb.append(longVal);
    }

    @Override
    public void writeDetailDescriptionTo(StringBuilder sb) {
        sb.append("累积量：").append(longVal);
    }

    @Override
    protected void forEachOneLevelChild(Consumer<BaseNBytePduClip<?>> consumer) {
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        M_IT_NA_1_InfoElem that = (M_IT_NA_1_InfoElem) o;
        return Float.compare(that.longVal, longVal) == 0;
    }

    @Override
    public int hashCode() {
        return Objects.hash(longVal);
    }
}
